package org.dromara.system.kernel;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailAlgorithmKernel {

    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 轮询组 本轮已收款账号 cache key
     */
    public static final String email_group_loops = "email_group_loops:";

    /**
     * 设置本轮发件邮箱账号
     *
     * @param agentId   代理ID
     * @param accountId 邮箱账号ID
     */
    public void setLoopAccount(String agentId, Long accountId) {
        String key = email_group_loops + agentId;
        redisTemplate.opsForZSet().add(key, accountId.toString(), Instant.now().getEpochSecond());
    }

    /**
     * 删除本轮发件邮箱记录
     *
     * @param agentId 代理ID
     */
    public void rmGroupLoop(String agentId) {
        String key = email_group_loops + agentId;
        redisTemplate.delete(key);
    }

    /**
     * 获取本轮已经发件邮箱列表
     *
     * @param agentId 代理ID
     */
    public List<Long> getLoopAccount(String agentId) {
        String key = email_group_loops + agentId;
        //获取所有记录
        Set<ZSetOperations.TypedTuple<String>> tupleSet = redisTemplate.opsForZSet().rangeWithScores(key, 0, -1);
        if (tupleSet == null) {
            return new ArrayList<>();
        }
        return tupleSet.stream().map(ZSetOperations.TypedTuple::getValue).filter(Objects::nonNull).map(Long::valueOf).collect(Collectors.toList());
    }

}

